<!-- 产线状态登记 -->
<template>
  <basic-container class="production-page">
    <avue-crud
      :option="option"
      :table-loading="loading"
      :defaults.sync="defaults"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="primary" icon="el-icon-plus" size="small" v-if="permission.equipmentStatusRegister_register" @click="$refs.crud.rowAdd()">登 记</el-button>
      </template>
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
      <!-- <template slot-scope="{ row }" slot="isDowntime">
        <el-tag>{{ row.isDowntime ? '是' : '否' }}</el-tag>
      </template> -->
    </avue-crud>
    <!-- 物料基础数据 弹框 -->
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </common-modal-template>
  </basic-container>
</template>
<script>
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { changeStateRecordDetail, changeStateRecord, changeRecordPage } from '@/api/product/equipmentStatusRegister';
import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
export default {
  name: '',
  components: {
    CommonModalTemplate,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'EQUIPMENT_STATUS_REGISTER',
      changeData: {},
      defaults: {},
      form: {},
      query: {},
      loading: false,
      data: [],
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      option: {
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 4,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: true,
        viewTitle: '详情',
        viewBtnText: '详情',
        addBtn: false,
        addTitle: '登记',
        editBtn: false,
        delBtn: false,
        selection: false,
        dialogClickModal: false,
        menu: true,
        menuWidth: 100,
        labelWidth: 130,
        columnBtn: false,
        column: [
          {
            label: '设备型号',
            span: 24,
            disabled: true,
            prop: 'equipmentModel'
          },
          {
            label: '设备编码',
            prop: 'equipmentNo',
            disabled: true,
            search: true,
            searchType: 'input',
            searchSpan: 4,
            type: 'search',
            span: 24,
            order: 1,
            appendClick: () => {
              this.assignment();
            },
            rules: [
              {
                required: true,
                message: '请输入设备编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '设备名称',
            prop: 'equipmentName',
            search: true,
            searchSpan: 4,
            order: 2,
            disabled: true,
            span: 24
          },
          {
            label: '产线',
            prop: 'lineName',
            disabled: true,
            span: 24
          },
          {
            label: '当前状态',
            prop: 'state',
            type: 'select',
            disabled: true,
            searchSpan: 4,
            search: true,
            span: 24,
            order: 3,
            // html: true,
            // formatter: (val) => {
            //   switch (val.state) {
            //     case '1':
            //       return `<span class="stateWords-success">正常</span>`;
            //     case '2':
            //       return `<span class="stateWords-primary">异常</span>`;
            //     case '3':
            //       return `<span class="stateWords-success">待检验</span>`;
            //     default:
            //       break;
            //   }
            // },
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=tooling_fixture_status',
            rules: [
              {
                required: true,
                message: '请选择当前状态',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '状态变更',
            prop: 'stateChange',
            hide: true,
            type: 'select',
            span: 24,
            order: 4,
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=tooling_fixture_status',
            rules: [
              {
                required: true,
                message: '请选择状态变更',
                trigger: 'blur'
              }
            ],
            change: ({ value, column }) => {
              this.changeEquipmentChangeStatusId(value);
            }
          },
          {
            label: '变更人',
            span: 24,
            prop: 'changedBy'
          },
          {
            label: '变更时间',
            prop: 'updateTime',
            type: 'date',
            searchSpan: 8,
            searchType: 'datetimerange',
            search: true,
            addDisplay: false,
            // disabled: true,
            span: 24,
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间'
          },
          {
            label: '变更原因',
            prop: 'reason',
            type: 'select',
            span: 24,
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            rules: [
              {
                required: true,
                message: '请输入变更原因',
                trigger: 'blur'
              }
            ],
            formatter: (row, value, label, column) => {
              if (value == '0') {
                return (label = '');
              } else {
                return label;
              }
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=equipment_change_reason'
          },
          {
            label: '变更前状态时长',
            span: 24,
            prop: 'durationFormat'
          },
          {
            label: '状态',
            prop: 'status',
            type: 'select',
            span: 24,
            dicData: [
              {
                label: '正常',
                value: 1
              },
              {
                label: '异常',
                value: 0
              }
            ],
            hide: true
          },
          {
            label: '备注',
            prop: 'remark',
            hide: true,
            span: 24,
            type: 'textarea',
            maxRows: 3,
            minRows: 3,
            maxlength: 300,
            showWordLimit: true
          }
        ]
      },
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      timer: new Date().getTime() //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        viewBtn: this.vaildData(this.permission.equipmentStatusRegister_view, false)
      };
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  methods: {
    rowSave(row, done, loading) {
      if (row.state == row.stateChange) {
        this.$message.warning('状态变更和当前状态一致，请重新选择');
        loading();
        return;
      }
      if (row.stateChange == '3' && row.reason == '') {
        this.$message.warning('状态变更为停机时，请选择变更原因');
        loading();
        return;
      }
      let param = {
        changeBy: this.changeData.changeBy || this.form.changeBy,
        changeTime: this.changeData.changeTime || this.form.changeTime,
        id: this.changeData.id,
        equipmentId: this.changeData.equipmentId,
        equipmentNo: this.changeData.equipmentNo,
        equipmentModel: this.changeData.equipmentModel,
        reason: Number(row.reason),
        state: Number(row.stateChange),
        fromState: row.state + '',
        remark: row.remark || this.form.changeTime
      };
      if (param.state === 1) {
        delete param.reason;
      }
      changeStateRecord(param)
        .then((res) => {
          this.$message.success('设备状态变更完成');
          this.onLoad(this.page, this.query);
          done();
        })
        .catch((err) => {
          loading();
        });
    },
    beforeOpen(done, type) {
      this.defaults.remark.display = true;
      if (['view'].includes(type)) {
        // 查看
        this.defaults.equipmentNo.type = 'input';
        this.defaults.status.display = true;
        this.defaults.changedBy.display = true;
        this.defaults.durationFormat.display = true;
        this.defaults.stateChange.display = false;
        // this.defaults.isDowntime.display = true;
        this.defaults.lineName.display = true;
        this.defaults.equipmentModel.display = true;
      } else {
        // 登记
        this.defaults.equipmentNo.type = 'search';
        this.defaults.status.display = false;
        this.defaults.changedBy.display = false;
        this.defaults.durationFormat.display = false;
        this.defaults.stateChange.display = true;
        // this.defaults.isDowntime.display = false;
        this.defaults.lineName.display = false;
        this.defaults.equipmentModel.display = false;
      }
      done();
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      if (params.changeTime && params.changeTime.length > 0) {
        params.startTime = params.changeTime[0];
        params.endTime = params.changeTime[1];
        delete params.changeTime;
      }
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    onLoad(page, params = {}) {
      this.loading = true;
      changeRecordPage(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records.map((rec) => {
          rec.changedBy = rec.createUserName;
          rec.equipmentNo = rec.equipmentCode;
          rec.fromState = rec.fromState === null ? '2' : rec.fromState + '';
          rec.state = rec.state + '';
          rec.reason = rec.remark;
          return rec;
        });
        setTimeout(() => {
          this.loading = false;
        }, 500);
      });
    },
    // 产线名称 弹框 配置
    assignment() {
      this.modalName = 'equipmentModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择设备（双击进行选择）',
        url: '/api/mes-product/ems-equipment/page?type=PRINTER',
        isPage: true,
        rowSelectionType: 'single',
        menu: false,
        editBtn: false,
        menuWidth: 100,
        columnDefs: [
          {
            label: '类型',
            // 设备类型：打印机PRINTER, 工具TOOL，辅料：AUXILIARY, 机器设备：MACHINE
            prop: 'equipmentType',
            search: true,
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=equipment_type',
            cascader: ['subType'], //级联属性
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            rules: [
              {
                required: true,
                message: '请选择类型',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '子类型',
            // 子类型：飞达/钢网/刮刀/锡膏
            prop: 'subType',
            type: 'select',
            dicFlag: false,
            dicUrl: '/api/blade-system/dict/dictionary?code={{key}}',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            rules: [
              {
                required: false,
                message: '请选择子类型',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '编码',
            prop: 'code',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '名称',
            prop: 'name',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '用途',
            prop: 'remarks',
            rules: [
              {
                required: false,
                message: '请描述用途',
                trigger: 'blur'
              }
            ]
          },
          {
            label: 'Ip',
            prop: 'ip',
            rules: [
              {
                required: false,
                message: '请输入Ip',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '端口',
            prop: 'port',
            rules: [
              {
                required: false,
                message: '请输入端口',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '主机名',
            prop: 'hostName',
            rules: [
              {
                required: false,
                message: '请输入主机名',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '协议类型',
            prop: 'protocol',
            rules: [
              {
                required: false,
                message: '请输入协议类型',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '负责人',
            prop: 'principalName',
            type: 'search',
            disabled: true,
            placeholder: '请选择 负责人',
            rules: [
              {
                required: false,
                message: '请选择负责人',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openUserCommonModal();
            }
          },
          {
            label: '联系方式',
            prop: 'contacts',
            hide: true,
            rules: [
              {
                required: false,
                message: '请输入联系方式',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '登录用户',
            prop: 'loginUser',
            hide: true,
            rules: [
              {
                required: false,
                message: '请输入登录用户名',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '登录密码',
            prop: 'loginPassword',
            type: 'password', //密码类型处理
            hide: true,
            rules: [
              {
                required: false,
                message: '请输入登录密码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '长',
            prop: 'length',
            type: 'number',
            precision: 2,
            minRows: 1,
            hide: true,
            rules: [
              {
                required: false,
                message: '请输入长',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '宽',
            prop: 'width',
            type: 'number',
            precision: 2,
            minRows: 1,
            hide: true,
            rules: [
              {
                required: false,
                message: '请输入宽',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '高',
            prop: 'height',
            type: 'number',
            precision: 2,
            minRows: 1,
            hide: true,
            rules: [
              {
                required: false,
                message: '请输入高',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '上次养护时间',
            prop: 'latestMaintain',
            type: 'datetime',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            hide: true
          },
          {
            label: '维修次数',
            prop: 'repairTimes',
            type: 'number',
            precision: 0,
            minRows: 1,
            hide: true,
            rules: [
              {
                required: true,
                message: '请输入维修次数',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '规格描述',
            prop: 'specification',
            hide: true,
            rules: [
              {
                required: false,
                message: '请输入规格描述',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '可用数量',
            prop: 'quantityAvailable',
            type: 'number',
            precision: 0,
            minRows: 1,
            hide: true,
            rules: [
              {
                required: false,
                message: '请输入可用数量',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '在用数量',
            prop: 'quantityReserved',
            type: 'number',
            precision: 0,
            minRows: 1,
            hide: true,
            rules: [
              {
                required: false,
                message: '请输入在用数量',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '单位',
            prop: 'uom',
            hide: true,
            rules: [
              {
                required: false,
                message: '请输入单位',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '最大使用次数',
            prop: 'maxUsage',
            type: 'number',
            precision: 0,
            minRows: 1,
            hide: true,
            rules: [
              {
                required: false,
                message: '请输入最大使用次数',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '已使用次数',
            prop: 'timesUsed',
            type: 'number',
            precision: 0,
            minRows: 1,
            hide: true,
            rules: [
              {
                required: false,
                message: '请输入已使用次数',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '固定资产原价',
            prop: 'fixedAssetCost',
            type: 'number',
            precision: 0,
            minRows: 1,
            hide: true,
            rules: [
              {
                required: false,
                message: '请输入固定资产原价',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '预计使用年限',
            prop: 'expectedLife',
            type: 'number',
            precision: 0,
            minRows: 1,
            hide: true,
            rules: [
              {
                required: false,
                message: '请输入预计使用年限',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '预计净残值率',
            // Estimated Residual Values
            prop: 'erv',
            type: 'number',
            precision: 0,
            minRows: 1,
            hide: true,
            rules: [
              {
                required: false,
                message: '请输入预计净残值率',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '制造商',
            prop: 'vendorName',
            type: 'search',
            disabled: true,
            hide: true,
            placeholder: '请选择 制造商',
            rules: [
              {
                required: false,
                message: '请选择制造商',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openPartnerCommonModal();
            }
          },
          {
            label: '组装成父设备',
            prop: 'parentId',
            hide: true,
            rules: [
              {
                required: false,
                message: '请输入组装成父设备',
                trigger: 'blur'
              }
            ]
          }
        ]
      };
    },
    // 获取选择的物料模态框行数据
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'equipmentModal':
          this.changeData.equipmentId = this._get(rowData, 'id', '');
          this.changeData.equipmentNo = this._get(rowData, 'code', '');
          this.changeData.equipmentName = this._get(rowData, 'name', '');
          this.changeData.equipmentModel = this._get(rowData, 'model', '');

          this.form.equipmentNo = this._get(rowData, 'code', '');
          this.form.equipmentName = this._get(rowData, 'name', '');
          this.form.equipmentModel = this._get(rowData, 'model', '');
          // 根据设备编码查询设备变更记录
          this.getEqChangeRecord(this.changeData.equipmentId);
          break;
        default:
          break;
      }
    },
    getEqChangeRecord(equipmentId) {
      changeStateRecordDetail(equipmentId)
        .then((res) => {
          if (res && res.status == 200) {
            let data = res.data.data;
            this.changeData.id = data.id;
            this.changeData.changeBy = data.changeBy;
            this.changeData.fromState = data.fromState === null ? '2' : data.fromState + '';
            this.changeData.state = data.state + '';
            this.changeData.changeTime = data.changeTime;
            this.changeData.remark = '';
            this.changeData.reason = data.reason === null ? '' : data.reason + '';

            this.form.fromState = data.fromState === null ? '2' : data.fromState + '';
            this.form.state = data.state + '';
            this.form.changeTime = data.changeTime;
            this.form.reason = data.reason === null ? '' : data.reason + '';
          }
        })
        .catch(() => {});
    },
    changeEquipmentChangeStatusId(value) {
      if (value == '3') {
        this.defaults.reason.rules[0].required = true;
        this.defaults.reason.display = true;
      } else {
        this.defaults.reason.rules[0].required = false;
        this.defaults.reason.display = false;
      }
      this.form.reason = '';
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>
<style lang="scss"></style>
